package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.StatusConstant;
import com.sky.context.ThreadLocalUtil;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BusinessException;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;
    @Override
    public Integer findByCategoryId(Long id) {
      Integer count = setmealMapper.findByCategoryId(id);
        return count;
    }

    @Override
    public void save(SetmealDTO setmealDTO) {
        String name = setmealDTO.getName();
        BigDecimal price = setmealDTO.getPrice();
        String description = setmealDTO.getDescription();
        if(!price.toString().matches("^(([1-9]{1}\\d*)|(0{1}))(\\.\\d{2})$")){
            throw new BusinessException("套餐价格格式有误，请输入大于零且最多保留两位小数的金额");
        }
        if(!description.matches("[0-9A-Za-z\\u4E00-\\u9FA5]{0,200}")){
            throw new BusinessException("套餐描述输入不符，请输入少于200个字");
        }

        if(!name.matches("[0-9A-Za-z\\u4E00-\\u9FA5]{3,20}")){
            throw new BusinessException("套餐名称输入不符，请输入3-20个字符");
        }
       Setmeal setmeal = setmealMapper.findByName(name);
       if(setmeal!= null && setmeal.getId()!= setmealDTO.getId()){
           throw new BusinessException("套餐名已被使用");
       }
       setmeal=new Setmeal();
        BeanUtil.copyProperties(setmealDTO,setmeal);
        setmeal.setStatus(StatusConstant.DISABLE);
       setmealMapper.save(setmeal);
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(CollectionUtil.isNotEmpty(setmealDishes)){
            for (SetmealDish setmealDish : setmealDishes) {
                setmealDish.setSetmealId(setmeal.getId());
            }
            setmealDishService.save(setmealDishes);
        }
    }

    @Override
    public PageResult findByPage(SetmealPageDTO dto) {
        Integer page = dto.getPage();
        Integer pageSize = dto.getPageSize();
        if(page==0){
            page=1;
        }
        if(pageSize==0){
            pageSize=5;
        }
        PageHelper.startPage(page,pageSize);
        List<SetmealVO> list = setmealMapper.findList(dto);
        PageInfo<SetmealVO> pageInfo = PageInfo.of(list);
        long total = pageInfo.getTotal();
        return new PageResult(total,list);
    }

    @Override
    public SetmealVO findById(Long id) {
        Setmeal setmeal = setmealMapper.findById(id);

      List<SetmealDish> setmealDishes =  setmealDishService.findBySetmealId(id);
        SetmealVO vo = BeanUtil.copyProperties(setmeal, SetmealVO.class);
        vo.setSetmealDishes(setmealDishes);
        return vo;
    }

    @Override
    public void update(SetmealDTO dto) {
        String name = dto.getName();
        BigDecimal price = dto.getPrice();
        String description = dto.getDescription();
        if(!price.toString().matches("/^((((?!0)\\d+)|(0{1}))(.\\d{1,2})?)$/")){
            throw new BusinessException("套餐价格格式有误，请输入大于零且最多保留两位小数的金额");
        }
        if(!description.matches("[0-9A-Za-z\\u4E00-\\u9FA5]{0,200}")){
            throw new BusinessException("套餐描述输入不符，请输入少于200个字");
        }

        if(!name.matches("[0-9A-Za-z\\u4E00-\\u9FA5]{3,20}")){
            throw new BusinessException("套餐名称输入不符，请输入3-20个字符");
        }

        Setmeal setmeal = setmealMapper.findByName(name);
        if(setmeal!= null && setmeal.getId()!= dto.getId()){
            throw new BusinessException("套餐名已被使用");
        }
        setmeal=new Setmeal();
        BeanUtil.copyProperties(dto,setmeal);
        setmealMapper.update(setmeal);
        setmealDishService.deleteBySetmealId(setmeal.getId());
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        if(CollectionUtil.isNotEmpty(setmealDishes)){
            for (SetmealDish setmealDish : setmealDishes) {
                setmealDish.setSetmealId(setmeal.getId());
            }
            setmealDishService.save(setmealDishes);
        }

    }

    @Override
    public void deleteByIds(Long[] ids) {
        if(ArrayUtil.isEmpty(ids)){
            throw new BusinessException("请选择要删除的套餐");
        }
       Integer count = setmealMapper.findByIds(ids);
        if(count>0){
            throw new BusinessException("在售套餐无法删除");
        }
        setmealMapper.deleteByIds(ids);
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Setmeal setmeal = Setmeal.builder()
                .status(status)
                .id(id)
                .build();
        setmealMapper.update(setmeal);
        if(status==StatusConstant.ENABLE){
         Integer count = dishService.findBySetmealId(id);
           if (count>0){
               throw new BusinessException("套餐有停售菜品无法上架");
           }
           //dishService.updateStatusBySetmealIds(ids,setmeal.getStatus());
        }
    }

    @Override
    public void updateStatusByDish(Long id, Integer status) {
        Long updateUser= ThreadLocalUtil.getCurrentId();
        LocalDateTime updateTime=LocalDateTime.now();
        setmealMapper.updateStatusByDish(id,status,updateTime,updateUser);
    }

    @Override
    public List<SetmealVO> findListByCategory4App(SetmealPageDTO pageDTO) {
        List<SetmealVO> list =setmealMapper.findList(pageDTO);
        return list;

    }


}
